package db

import (
	"context"
	"github.com/go-redis/redis/v8"
	config2 "iot-base/common/config"
	"time"
)

var Rdb *redis.Client

func init() {
	Rdb = redis.NewClient(&redis.Options{
		Addr:     config2.DBOption.RedisOption.Addr,
		Password: config2.DBOption.RedisOption.Password, // no password set
		DB:       config2.DBOption.RedisOption.Index,    // use default DB
		PoolSize: 2,
	})
}

type RedisCli struct {
	rdb *redis.Client
	ctx context.Context
}

func NewRedis() *RedisCli {
	return &RedisCli{
		rdb: Rdb,
		ctx: context.Background(),
	}
}

func (r *RedisCli) Get(key string) (string, error) {
	return r.rdb.Get(r.ctx, key).Result()
}

func (r *RedisCli) Set(key string, value interface{}, expiration time.Duration) (string, error) {
	return r.rdb.Set(r.ctx, key, value, expiration).Result()
}

func (r *RedisCli) HGetAll(key string) (map[string]string, error) {
	return r.rdb.HGetAll(r.ctx, key).Result()
}

func (r *RedisCli) HMSet(key string, value map[string]interface{}) error {
	return r.rdb.HMSet(r.ctx, key, value).Err()
}

func (r *RedisCli) HSet(myhash string, key, value string) (int64, error) {
	return r.rdb.HSet(r.ctx, myhash, key, value).Result()
}
func (r *RedisCli) HGet(key, field string) (string, error) {
	return r.rdb.HGet(r.ctx, key, field).Result()
}
func (r *RedisCli) HDel(key string, key2 ...string) error {
	return r.rdb.HDel(r.ctx, key, key2...).Err()
}

func (r *RedisCli) Expire(key string, expiration time.Duration) error {
	return r.rdb.Expire(r.ctx, key, expiration).Err()
}

func (r *RedisCli) Del(keys ...string) error {
	return r.rdb.Del(r.ctx, keys...).Err()
}

func (r *RedisCli) IncrBy(key string, value int64) (int64, error) {
	return r.rdb.IncrBy(r.ctx, key, value).Result()
}

func (r *RedisCli) HIncrBy(key string, field string, incr int64) (int64, error) {
	return r.rdb.HIncrBy(r.ctx, key, field, incr).Result()
}
